package com.kelvin.paopao.module.person.edit;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.airsaid.pickerviewlibrary.CityPickerView;
import com.airsaid.pickerviewlibrary.OptionsPickerView;
import com.airsaid.pickerviewlibrary.TimePickerView;
import com.airsaid.pickerviewlibrary.listener.OnSimpleCitySelectListener;
import com.bumptech.glide.Glide;
import com.kelvin.kelvinlib.utils.CommonUtil;
import com.kelvin.kelvinlib.utils.LogUtil;
import com.kelvin.paopao.R;
import com.kelvin.paopao.api.responseBean.PersonPhotoModel;
import com.kelvin.paopao.api.responseBean.TalkPriceModel;
import com.kelvin.paopao.api.responseBean.UserDetailModel;
import com.kelvin.paopao.injector.components.DaggerPersonDetailEditComponent;
import com.kelvin.paopao.injector.modules.PersonDetailEditModule;
import com.kelvin.paopao.module.base.BaseActivity;
import com.kelvin.paopao.module.person.detail.PersonDetailActivity;
import com.kelvin.paopao.module.person.editmore.PersonDetailEditMoreActivity;
import com.kelvin.paopao.module.person.tagset.SetTagActivity;
import com.kelvin.paopao.widgets.CustomToolbar;
import com.kelvin.paopao.widgets.PersonPhotoEditView;
import com.kelvin.paopao.widgets.dialog.OptionSelector;
import com.kelvin.paopao.widgets.dialog.SetChatMoneyDialogFragment;
import com.kelvin.paopao.widgets.dialog.SetPSMoneyDialogFragment;
import com.lwkandroid.imagepicker.ImagePicker;
import com.lwkandroid.imagepicker.data.ImageBean;
import com.lwkandroid.imagepicker.data.ImagePickType;
import com.lwkandroid.imagepicker.utils.GlideImagePickerDisplayer;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by MCK on 2017/5/11.
 */

public class PersonDetailEditActivity extends BaseActivity<IPersonDetailEditPresenter>
        implements IPersonDetailEditView {
    @BindView(R.id.custom_toolbar)
    CustomToolbar customToolbar;
    @BindView(R.id.iv)
    CircleImageView iv;
    @BindView(R.id.iv_gender)
    ImageView ivGender;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.recycler_view)
    PersonPhotoEditView recyclerView;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_age_edit)
    TextView tvAgeEdit;
    @BindView(R.id.tv_tall)
    TextView tvTall;
    @BindView(R.id.tv_weight)
    TextView tvWeight;
    @BindView(R.id.tv_professional)
    TextView tvProfessional;
    @BindView(R.id.tv_location_edit)
    TextView tvLocationEdit;
    @BindView(R.id.tv_relationship)
    TextView tvRelationship;
    @BindView(R.id.et_qianming)
    EditText etQianming;

    @BindView(R.id.tv_ps_money)
    TextView tvPsMoney;


    private static final int REQUEST_CODE_FOR_NICKNAME = 1001;
    private static final int REQUEST_CODE_FOR_PROFESSIONAL = 1002;
    private static final int REQUEST_CODE_FOR_IMG = 1003;
    private static final int REQUEST_CODE_FOR_PhOTO = 1004;
    private static final int REQUEST_CODE_FOR_TAG = 1005;
    private static final int REQUEST_CODE_FOR_HEIGHT = 1006;


    @BindView(R.id.tv_talk_money)
    TextView tvTalkMoney;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout idFlowlayout;

    private String user_label;
    private String user_name, user_age, user_zhiye, user_tizhong,
            user_shengao, user_provice, user_city, user_qinggan, user_qianming;


    /**
     * 时间选择器
     */
    private TimePickerView mTimePickerView;

    private TagAdapter tagAdapter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_person_detail_edit;
    }

    @Override
    protected void initInjector() {
        DaggerPersonDetailEditComponent.builder().personDetailEditModule(new PersonDetailEditModule(this))
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        customToolbar.showBackIcon(this);
        customToolbar.setTitle("编辑个人详情");
        customToolbar.inflateMenu(R.menu.menu_update_info);
        customToolbar.setMenuOnClick(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                updateInfo();
                return true;
            }
        });

        recyclerView.create(this);
        recyclerView.setListener(new PersonPhotoEditView.AddImgListner() {
            @Override
            public void addImage() {
                pickImage(REQUEST_CODE_FOR_PhOTO);
            }
        });
    }

    @Override
    protected void updateViews(boolean isRefresh) {
        mPresenter.getData(isRefresh);
        mPresenter.getTalkMoney();
    }

    @OnClick({R.id.ll_nickname, R.id.ll_age, R.id.ll_tall, R.id.ll_weight,
            R.id.ll_professional, R.id.ll_location,
            R.id.ll_relationship, R.id.iv, R.id.ll_talk_money, R.id.ll_tag, R.id.ll_ps_price})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_nickname:
                Intent intent = new Intent(PersonDetailEditActivity.this, PersonDetailEditMoreActivity.class);
                intent.setAction(PersonDetailEditMoreActivity.TYPE_EDIT_NICKNAME);
                startActivityForResult(intent, REQUEST_CODE_FOR_NICKNAME);
                break;
            case R.id.iv:
                pickImage(REQUEST_CODE_FOR_IMG);
                break;
            case R.id.ll_age:
                showTimePickDialog();
                break;
            case R.id.ll_tall:
//                OptionSelector.showTallSelector(this).setOnOptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
//                    @Override
//                    public void onOptionsSelect(int option1, int option2, int option3) {
//                        tvTall.setText(OptionSelector.tallList.get(option1));
//                        user_shengao = OptionSelector.tallList.get(option1);
//                    }
//                });
                intent = new Intent(PersonDetailEditActivity.this, PersonDetailEditMoreActivity.class);
                intent.setAction(PersonDetailEditMoreActivity.TYPE_EDIT_HEIGHT);
                startActivityForResult(intent, REQUEST_CODE_FOR_HEIGHT);
                break;
            case R.id.ll_weight:
                OptionSelector.showWeightSelector(this).setOnOptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int option1, int option2, int option3) {
                        tvWeight.setText(OptionSelector.weightList.get(option1));
                        user_tizhong = OptionSelector.weightList.get(option1);
                    }
                });
                break;
            case R.id.ll_professional:
                intent = new Intent(PersonDetailEditActivity.this, PersonDetailEditMoreActivity.class);
                intent.setAction(PersonDetailEditMoreActivity.TYPE_EDIT_PROFESSIONAL);
                startActivityForResult(intent, REQUEST_CODE_FOR_PROFESSIONAL);
                break;

            case R.id.ll_location:
                showHomeTownDialog();
                break;
            case R.id.ll_tag:
                intent = new Intent(this, SetTagActivity.class);
                intent.putExtra("setTag", user_label);
                startActivityForResult(intent, REQUEST_CODE_FOR_TAG);
                break;
            case R.id.ll_relationship:
                OptionSelector.showRelationShipSelector(this).setOnOptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int option1, int option2, int option3) {
                        tvRelationship.setText(OptionSelector.relationShip.get(option1));
                        user_qinggan = OptionSelector.relationShip.get(option1);
                    }
                });
                break;
            case R.id.ll_talk_money:
                SetChatMoneyDialogFragment dialogFragment = SetChatMoneyDialogFragment.newInstance();
                dialogFragment.setListener(new SetChatMoneyDialogFragment.OnSetCompleteListener() {
                    @Override
                    public void onSetComplete() {
                        mPresenter.getTalkMoney();
                    }
                });
                dialogFragment.show(getSupportFragmentManager(), "SetChatMoneyDialogFragment");
                break;
            case R.id.ll_ps_price:
                SetPSMoneyDialogFragment psMoneyDialogFragment = SetPSMoneyDialogFragment.newInstance();
                psMoneyDialogFragment.setListener(new SetPSMoneyDialogFragment.OnSetCompleteListener() {
                    @Override
                    public void onSetComplete() {
                        mPresenter.getPsPrice();
                    }
                });
                psMoneyDialogFragment.show(getSupportFragmentManager(), "SetChatMoneyDialogFragment");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_FOR_NICKNAME) {
                tvNickname.setText(data.getStringExtra("data"));
            } else if (requestCode == REQUEST_CODE_FOR_PROFESSIONAL) {
                tvProfessional.setText(data.getStringExtra("data"));
            } else if (requestCode == REQUEST_CODE_FOR_HEIGHT) {
                tvTall.setText(data.getStringExtra("data"));
            } else if (requestCode == REQUEST_CODE_FOR_IMG) {
                List<ImageBean> resultList = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA);
                Glide.with(this).load(new File(resultList.get(0).getImagePath())).into(iv);
            } else if (requestCode == REQUEST_CODE_FOR_TAG) {
                user_label = data.getStringExtra("result");
                if (!TextUtils.isEmpty(user_label)) {
                    tagAdapter = new TagAdapter<String>(user_label.split("\\|")) {
                        @Override
                        public View getView(FlowLayout parent, int position, String s) {
                            TextView tv = (TextView) LayoutInflater.from(PersonDetailEditActivity.this)
                                    .inflate(R.layout.tag_item,
                                            idFlowlayout, false);
                            tv.setText(s);
                            return tv;
                        }
                    };
                    idFlowlayout.setAdapter(tagAdapter);
                }
            } else {
                List<ImageBean> resultList = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA);
                recyclerView.addImageView(resultList.get(0).getImagePath());
            }
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent(context, PersonDetailEditActivity.class);
        context.startActivity(intent);
    }

    /**
     * 进入图片选择器
     */
    private void pickImage(int request_code) {
        //发起图片选择
        new ImagePicker.Builder()
                .pickType(ImagePickType.SINGLE) //设置选取类型(拍照ONLY_CAMERA、单选SINGLE、多选MUTIL)
                .needCamera(true) //是否需要在界面中显示相机入口(类似微信那样)
                .displayer(new GlideImagePickerDisplayer()) //自定义图片加载器，默认是Glide实现的,可自定义图片加载器
                .build()
                .start(this, request_code, Activity.RESULT_OK); //自定义RequestCode和ResultCode
    }

    /**
     * 展示日期选择器
     */
    private void showTimePickDialog() {
        mTimePickerView = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        mTimePickerView.setTime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        mTimePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                user_age = format.format(date);
                tvAgeEdit.setText(user_age);
            }
        });
        mTimePickerView.show();
    }

    private CityPickerView mCityPickerView;

    /**
     * 展示地址选择器
     */
    private void showHomeTownDialog() {
        mCityPickerView = new CityPickerView(this);
        mCityPickerView.setOnCitySelectListener(new OnSimpleCitySelectListener() {
            @Override
            public void onCitySelect(String prov, String city, String area) {
                // 省、市、区 分开获取
                tvLocationEdit.setText(prov + "  " + city);
                user_provice = prov;
                user_city = city;
            }

            @Override
            public void onCitySelect(String str) {
                // 一起获取
            }
        });
        mCityPickerView.show();
    }


    @Override
    public void loadData(UserDetailModel info) {
        user_label = info.getUser_Label();
        if (!TextUtils.isEmpty(user_label)) {
            tagAdapter = new TagAdapter<String>(user_label.split("\\|")) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) LayoutInflater.from(PersonDetailEditActivity.this)
                            .inflate(R.layout.tag_item,
                                    idFlowlayout, false);
                    tv.setText(s);
                    return tv;
                }
            };
            idFlowlayout.setAdapter(tagAdapter);
        }

        String user_ps_price = info.getUser_ps_price();
        tvPsMoney.setText(user_ps_price);

        if (info.getUser_sex() == 1) {
            ivGender.setImageResource(R.drawable.icon_male_color);
        } else {
            ivGender.setImageResource(R.drawable.icon_female_color);
        }

        if (!TextUtils.isEmpty(info.getUser_age())) {
            tvAgeEdit.setText(info.getUser_age());
            tvAge.setText(CommonUtil.getAge(info.getUser_age()) + "岁");
        }

        if (!TextUtils.isEmpty(info.getUser_city()) || !TextUtils.isEmpty(info.getUser_province())) {
            tvLocationEdit.setText(info.getUser_province() + " " + info.getUser_city());
            tvLocation.setText(info.getUser_province() + " " + info.getUser_city());
        }

        if (!TextUtils.isEmpty(info.getUser_ganqing())) {
            tvRelationship.setText(info.getUser_ganqing());
        }

        if (!TextUtils.isEmpty(info.getUser_name())) {
            tvNickname.setText(info.getUser_name());
        }

        if (!TextUtils.isEmpty(info.getUser_qianming())) {
            etQianming.setText(info.getUser_qianming());
        }

        if (!TextUtils.isEmpty(info.getUser_shengao())) {
            tvTall.setText(info.getUser_shengao());
        }

        if (!TextUtils.isEmpty(info.getUser_tizhong())) {
            tvWeight.setText(info.getUser_tizhong());
        }

        if (!TextUtils.isEmpty(info.getUser_ganqing())) {
            tvRelationship.setText(info.getUser_ganqing());
        }
        if (!TextUtils.isEmpty(info.getUser_zhiye())) {
            tvProfessional.setText(info.getUser_zhiye());
        }

        Glide.with(this).load(info.getUser_headimg()).placeholder(R.drawable.default_img).
                error(R.drawable.default_img).into(iv);
    }

    @Override
    public void loadPersonPhoto(List<PersonPhotoModel> photos) {
        recyclerView.setNetWorkImage(photos);
    }

    @Override
    public void updateTalkMoney(TalkPriceModel model) {
        tvTalkMoney.setText(model.getUser_talk_price() + "元/小时");
    }

    private void updateInfo() {
        user_name = tvNickname.getText().toString();
        if (user_name.equals("请填写")) {
            user_name = null;
        }
        user_qianming = etQianming.getText().toString();
        user_zhiye = tvProfessional.getText().toString();
        if (user_zhiye.equals("请填写")) {
            user_zhiye = null;
        }

        mPresenter.updateInfo(user_name, user_age, user_qianming, user_zhiye,
                user_tizhong, user_shengao, user_provice, user_city, user_qinggan, user_label);
    }
}
